from rest_framework import serializers
from .models import Region

# 树结构
class RegionLazyTreeSerializer(serializers.ModelSerializer):
    label = serializers.CharField(source="name")
    value = serializers.CharField(source="code")
    hasChildren = serializers.SerializerMethodField()

    def get_hasChildren(self,obj):
        return obj.region_set.exists()

    class Meta:
        model = Region
        fields = ['parentCode','label','value','hasChildren']

# 字典详情
class DetailSerializer(serializers.ModelSerializer):
    code = serializers.CharField()
    parentName = serializers.SerializerMethodField()
    parentCode = serializers.SerializerMethodField()

    def get_parentName(self,obj):
        return obj.parentCode.name if obj.parentCode else None
    
    def get_parentCode(self,obj):
        return str(obj.parentCode.code) if obj.parentCode else None
    
    class Meta:
        model = Region
        fields = "__all__"

# 调试
class SelectSerializer(serializers.ModelSerializer):
    label = serializers.CharField(source="name")
    value = serializers.CharField(source="code")
    
    class Meta:
        model = Region
        fields = ['label','value']
